package com.designpattern.softwaredesignpatternstudy.pdai.singleton;

import java.io.Serializable;

/**
 * @author: Aster
 * @note: 懒汉式-双重校验锁
 * @create: 2025-07-16 15:17
 **/
public class Singleton04 implements Serializable {

    private static final long serialVersionUID = 7017343875362379197L;

    /**
     * instance = new Singleton04();会分为三部
     * 1、分配内存空间
     * 2、初始化对象
     * 3、将instance对象指向分配的内存空间
     * 如果不加volatile关键字，可能会发生JVM指令重排
      */
    private volatile static Singleton04 instance;

    private Singleton04() {
        if (instance != null) {
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }

    public static Singleton04 getInstance() {
        if (instance == null) {
            synchronized (Singleton04.class) {
                if (instance == null) {
                    instance = new Singleton04();
                }
            }
        }
        return instance;
    }

    protected Object readResolve() {
        return getInstance();
    }
}
